//
//  JwWebJSController.m
//  JwPack
//
//  Created by 陈警卫 on 2024-08-27.
//

#import "JwWebJSController.h"
#import "JwWebView.h"

@interface JwWebJSController ()<JwWebViewDelegate>

@property (nonatomic, strong) JwWebView *jwWebView;

@end

@implementation JwWebJSController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupView];
    [self setupData];
}

- (void)setupData {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"JSOC" ofType:@"html"];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    NSURLRequest *fileRequest = [NSURLRequest requestWithURL:fileURL];
    [self.jwWebView.webView loadRequest:fileRequest];
    
    //[self.jwWebView.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://cn-uat.iot.dreame.tech:8080/goCaptcha.html?lang=zh&foreign=false&timestamp=1743646602574608"]]];
}

- (void)setupView {
    
    CGFloat navHeight = [JwScreen navBatBarHeight];
    self.jwWebView = [[JwWebView alloc] initWithFrame:(CGRectMake(0, navHeight, self.view.jw_width, self.view.jw_height - navHeight))];
    self.jwWebView.delegate = self;
    [self.view addSubview:self.jwWebView];
    
    kJwWeak(self);
    // title回调
    self.jwWebView.didObserveTitle = ^(NSString * _Nonnull title) {
        wself.title = title;
    };
    // 下拉回调
    self.jwWebView.didHeaderRefreshing = ^(UIScrollView * _Nonnull scrollView) {
        
    };
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"OCJS" style:(UIBarButtonItemStylePlain) target:self action:@selector(ocjsAction)];
}

/// js调用oc回调
- (void)webViewReceiveScriptMessage:(WKScriptMessage *)message {
    DLog(@"name:%@ body:%@ frameInfo:%@",message.name,message.body,message.frameInfo);
    NSString *param = [NSString stringWithFormat:@"name:%@\nbody:%@", message.name, message.body];
    
    [JwAlerter showAlertWithTitle:@"js调用oc" message:param otherTitles:@[@"确定"] handler:^(UIAlertAction * _Nonnull action, NSInteger index) {
        
    }];
    
}

- (void)ocjsAction {
    NSString *jsString = [NSString stringWithFormat:@"changeColor()"];
    [self.jwWebView setupJavaScript:jsString];
}


@end
